package com.service.impl;

import com.common.contant.RestResponse;
import com.common.exception.TaoExceptionEnum;
import com.common.utils.BeanHelper;
import com.common.vo.PageResult;
import com.dao.mapper.TbSpuDetailMapper;
import com.dao.mapper.TbSpuMapper;
import com.dto.BrandDTO;
import com.dto.CategoryDTO;
import com.dto.TbSpuDTO;
import com.entity.TbSpu;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import com.service.GoodsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Author: sijunqiang
 * @Date: 2020/6/4 19:11
 * @Description: 商品服务的业务层
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class GoodsServiceImpl implements GoodsService {

    private final TbSpuMapper tbSpuMapper;

    private final TbSpuDetailMapper tbSpuDetailMapper;

    private final CategoryServiceImpl categoryService;

    private final BrandServiceImpl brandService;


    /**
     * 查询spu分页
     *
     * @return
     */
    @Override
    public RestResponse querySpuByPage(Integer page, Integer rows, Boolean saleable, String key) {
        // 分页
//        Page  result = PageHelper.startPage(page, rows);
        Page result = new Page();

        // 添加搜索条件
        Example example = new Example(TbSpu.class);
        Example.Criteria criteria = example.createCriteria();
        // 关键字过滤  `name`
        if (StringUtils.isNotBlank(key)) criteria.andLike("name", "%" + key + "%");
         //上下架过滤
        //   if (saleable != null) criteria.andEqualTo("saleable", saleable);
//        //按照时间降序
//        example.setCountProperty("update_time DESC");
        List<TbSpu> spuList1 = tbSpuMapper.selectByExample(example);

        int i = tbSpuMapper.selectCountByExample(example);
        Optional<List<TbSpu>> optional = Optional.ofNullable(tbSpuMapper.selectByExample(example));

        if (!optional.isPresent()) return RestResponse.error(TaoExceptionEnum.GOODS_NOT_FOUND);

        // 转换数据
        List<TbSpu> spuList = optional.get();
        List<TbSpuDTO> tbSpuDTOList = BeanHelper.copyWithCollection(spuList, TbSpuDTO.class);
        //组装数据
        handCategoryAndBrandName(tbSpuDTOList);
        return RestResponse.success(new PageResult<>(result.getTotal(), result.getPages(), tbSpuDTOList));
    }


    // 处理分类和品牌的名称
    private void handCategoryAndBrandName(List<TbSpuDTO> tbSpuDTOList) {
        // 设置新的品牌的名称
        // 1：获取品牌的id集合
        List<Long> brandIdList = tbSpuDTOList.stream().map(TbSpuDTO::getBrandId).collect(Collectors.toList());

        // 2：根据品牌的id集合  然后保存到一个map集合中 key是品牌的id value是品牌的name
        List<BrandDTO> brandDTOS = brandService.queryByIds(brandIdList);
        Map<Long, String> brandNameMap = brandDTOS.stream().collect(Collectors.toMap(BrandDTO::getId, BrandDTO::getName));

        // 设置分类的名称
        // 根据分类的id集合批量获取分类的name
        tbSpuDTOList.stream().forEach(tbSpuDTO -> {
            List<Long> categoryIds = tbSpuDTO.getCategoryIds();
            String categoryName = categoryService.queryByIdList(categoryIds).stream().map(CategoryDTO::getName).collect(Collectors.joining("/"));
            // 设置新的分类的名称
            tbSpuDTO.setCategoryName(categoryName);
            //设置新的品牌的名称
            tbSpuDTO.setBrandName(brandNameMap.get(tbSpuDTO.getBrandId()));
        });


    }

}
